<?php

class AuditableListener extends Doctrine_AuditLog_Listener
{

	public function __construct(AuditableLog $auditLog)
	{
		$this->_auditLog = $auditLog;
	}
	
	public function postInsert(Doctrine_Event $event) 
	{
		if ($this->_auditLog->isAuditable())
		{
			$record  = $event->getInvoker();

			$this->createVersion($record);
		}
	}

	public function preUpdate(Doctrine_Event $event)
	{
		if ($this->_auditLog->isAuditable())
		{
			$record = $event->getInvoker();
			$version = $this->_auditLog->getOption('version');
			$record->set($version['name'], $this->_getNextVersion($record));
			$this->createVersion($record);
		}
	}

	protected function createVersion(Doctrine_Record $record)
	{
		if (sfContext::hasInstance())
		{
			$class = $this->_auditLog->getOption('className');

			$version = new $class();
			$version->merge($record->toArray(), false);
			$version->usuario = sfContext::getInstance()->getUser()->getUsername();
			$version->ip = sfContext::getInstance()->getRequest()->getRemoteAddress();
			$version->fecha = date('Y-m-d H:i:s', time());
			$version->save();
			$this->createRelationVersion($record, $version->version);
		}
	}

	protected function createRelationVersion(Doctrine_Record $record, $version)
	{
		foreach ($this->_auditLog->getOption('relations') as $field => $relationName)
		{
			$relation = $record->getTable()->getRelation($relationName);
			$component = $relation->getAssociationTable()->getComponentName();
			$class = $component . 'Version'; //FIXME

			foreach ($record->get($relation['alias'], false) as $child)
			{
				$relationVersion = new $class();
				$relationVersion->set($relation->getForeignFieldName(), $child->id);
				$relationVersion->set($relation->getLocalFieldName(), $record->id);
				$relationVersion->set('version', $version);
				$relationVersion->save();
			}
		}
	}

}
